##
##    This file is part of Metrix.
##
##    Metrix is free software: you can redistribute it and/or modify
##    it under the terms of the GNU General Public License as published by
##    the Free Software Foundation, either version 3 of the License, or
##    (at your option) any later version.
##
##    Metrix is distributed in the hope that it will be useful,
##    but WITHOUT ANY WARRANTY; without even the implied warranty of
##    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##    GNU General Public License for more details.
##
##    You should have received a copy of the GNU General Public License
##    along with Metrix.  If not, see <http://www.gnu.org/licenses/>.
##

require 'digest/sha2'
class User < ActiveRecord::Base
	has_and_belongs_to_many :roles	
	validates_uniqueness_of :username
	def self.authenticate(username, password)
	  user = User.find(:first, :conditions => ['username = ?' , username])
	  if user.blank? ||
	    Digest::SHA256.hexdigest(password + user.password_salt) != user.password_hash
	    raise "El nombre de usuario o la contraseña son incorrectos"
	  end
	  user
	end

  def password=(pass)
    salt = [Array.new(6){rand(256).chr}.join].pack("m").chomp
    self.password_salt, self.password_hash = salt, Digest::SHA256.hexdigest(pass + salt)
  end

  def to_s
   "#{username}"
  end

end

